-- intervalCall
--
local import = import
---@type behavior_ret
local bret = import('bt/bt_plugin/behavior3/behavior_ret')
local string = string
local M = {
    name = "IntervalCall",
    type = "Composite",
    desc = "间隔执行",
    args = {
        { "time", "int?", "时间/秒" },
        { "firstCall", "boolean?", "首次是否调用" },
        { "minRandomTime", "int?", "最小随机时间/秒" },
        { "maxRandomTime", "int?", "最大随机时间/秒" },
    },
}

function M.run(node, env)
    math.randomseed(os.time())
    local owner = env.owner
    local key = string.format("%s#%d_intervalCall", node.tree.name, node.id)
    local cfgTime = node.args.time
    local firstCall = node.args.firstCall
    local minRandomTime = node.args.minRandomTime
    local maxRandomTime = node.args.maxRandomTime
    local time = owner:get_timer_time(key)
    local last_idx, last_ret = node:resume(env)
    local isRun = false
    if not time then
        if minRandomTime and maxRandomTime then
            cfgTime = math.random(minRandomTime, maxRandomTime)
        end
        owner:add_timer(key, cfgTime, nil, false, false, true)
    end
    if last_idx then
        if last_ret == bret.RUNNING then
            return last_ret
        end
        last_idx = last_idx + 1
        isRun = true
    else
        last_idx = 1
    end
    if isRun or (not time and firstCall) or (time and time <= 0) then
        for i = last_idx, #node.children do
            local child = node.children[i]
            local r = child:run(env)
            if r == bret.RUNNING then
                return node:yield(env, i)
            end
        end
        if minRandomTime and maxRandomTime then
            cfgTime = math.random(minRandomTime, maxRandomTime)
        end
        owner:set_timer_defTime(key, cfgTime)
        return bret.SUCCESS
    end
    return bret.FAIL
end

return M
